package sql

import (
	"context"

	"github.com/opentracing/opentracing-go"
)

// traceContext 用于保存trace上下文
type traceContext struct {
	tracer  opentracing.Tracer
	spanCtx opentracing.SpanContext
}

func Trace(ctx context.Context, tracers ...opentracing.Tracer) *traceContext {
	if ctx == nil {
		return traceWithSpanContext(nil, tracers...)
	}

	span := opentracing.SpanFromContext(ctx)
	if span != nil {
		return traceWithSpanContext(span.Context(), tracers...)
	}

	return traceWithSpanContext(nil, tracers...)
}

func traceWithSpanContext(ctx opentracing.SpanContext, tracers ...opentracing.Tracer) *traceContext {
	var tracer opentracing.Tracer
	if len(tracers) > 0 {
		tracer = tracers[0]
	} else {
		tracer = opentracing.GlobalTracer()
	}

	tc := &traceContext{}
	tc.tracer = tracer
	tc.spanCtx = ctx
	return tc
}
